document.addEventListener('DOMContentLoaded', () => {
  const searchForm = document.querySelector('.search-form');
  const searchInput = document.querySelector('.search-box');
  const tableBody = document.querySelector('#table-body');
  const tableHead = document.querySelector('#table-head');
  const loadingIndicator = document.querySelector('#loading');
  const errorMessage = document.querySelector('#error');
  const dataContainer = document.querySelector('#data-container');
  
  // Load initial data
  loadData();
  
  // Handle search form submission
  searchForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const query = searchInput.value.trim();
    
    if (query) {
      // Redirect to search page with query
      window.location.href = `/search.html?query=${encodeURIComponent(query)}`;
    }
  });
  
  // Load and display data
  async function loadData() {
    try {
      loadingIndicator.style.display = 'block';
      errorMessage.style.display = 'none';
      dataContainer.style.display = 'none';
      
      const response = await fetch('/api/data');
      
      if (!response.ok) {
        throw new Error('Failed to fetch data');
      }
      
      const data = await response.json();
      
      if (!Array.isArray(data)) {
        throw new Error('Invalid data format received');
      }
      
      displayData(data);
      
    } catch (error) {
      errorMessage.textContent = error.message;
      errorMessage.style.display = 'block';
    } finally {
      loadingIndicator.style.display = 'none';
    }
  }
  
  // Display data in table
  function displayData(data) {
    if (!Array.isArray(data) || data.length === 0) {
      errorMessage.textContent = 'No data available';
      errorMessage.style.display = 'block';
      return;
    }
    
    // Create table headers
    const headerRow = document.createElement('tr');
    const headers = Object.keys(data[0] || {});
    
    headers.forEach(header => {
      const th = document.createElement('th');
      th.textContent = header.charAt(0).toUpperCase() + header.slice(1); // Capitalize first letter
      headerRow.appendChild(th);
    });
    
    tableHead.innerHTML = '';
    tableHead.appendChild(headerRow);
    
    // Create table rows
    tableBody.innerHTML = '';
    data.forEach(item => {
      if (!item) return; // Skip if item is null or undefined
      
      const row = document.createElement('tr');
      
      headers.forEach(header => {
        const cell = document.createElement('td');
        if (header === 'id' || header === 'ISBN') {
          const link = document.createElement('a');
          link.href = `/detail.html?id=${item[header]}`;
          link.textContent = item[header];
          cell.appendChild(link);
        } else {
          cell.textContent = item[header] || '';
        }
        row.appendChild(cell);
      });
      
      tableBody.appendChild(row);
    });
    
    dataContainer.style.display = 'block';
  }
});
